/*
Package captcha
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/2/20 18:43
@File     : store_redis.go
@Project  : gohub
@Desc     :
*/
package captcha

import (
	"errors"
	"gohub/pkg/app"
	"gohub/pkg/config"
	"gohub/pkg/redis"
	"time"
)

// RedisStore 实现base64Captcha.Store interface
type RedisStore struct {
	RedisClient *redis.RedisClient
	KeyPrefix   string
}

// Set 实现base64Captcha.Store interface的Set方法
func (s *RedisStore) Set(key string, value string) error {
	ExpireTime := time.Minute * time.Duration(config.GetInt64("captcha.expire_time"))
	//用于本地开发调试
	if app.IsLocal() {
		ExpireTime = time.Minute * time.Duration(config.GetInt64("captcha.debug_expire_time"))
	}

	if ok := s.RedisClient.Set(s.KeyPrefix+key, value, ExpireTime); !ok {
		return errors.New("无法存储图片验证码答案")
	}
	return nil
}

// Get 实现base64Captcha.Store interface的Get方法，用于获取存储的验证码答案
func (s *RedisStore) Get(key string, clear bool) string {
	key = s.KeyPrefix + key
	val := s.RedisClient.Get(key)
	//获取验证码后是否直接删除缓存中的该验证码数据
	if clear {
		s.RedisClient.Del(key)
	}
	return val
}

// Verify 实现base64Captcha.Store interface的Verify方法，用于获取存储的验证码答案
func (s *RedisStore) Verify(key, answer string, clear bool) bool {
	v := s.Get(key, clear)
	//验证用户提交验证码是否正确
	return v == answer
}
